# -*- coding: utf-8 -*-
import typing

from django.core.handlers.wsgi import WSGIRequest

from firstDjango.exceptions import FormException
from index.common.paging import page2offset
from index.common.tool import DATE_TIME_FMT, get_url
from index.dao import comment_dao
from index.models import CommentLike, BookComment


def add_comment(user_id, book_id, score, content):
    return comment_dao.add_comment(user_id, book_id, score, content)


def delete_comment(user_id, comment_id):
    return comment_dao.delete_comment(user_id, comment_id)


def update(user_id, comment_id, rate=None, content=None):
    comment_dao.update(user_id, comment_id, rate, content)


def comment_model2dict(req, comments, is_like: typing.Callable[[BookComment], bool], book_id=None):
    comment_dicts = [
        {
            "id": comment.id, "content": comment.content,
            "rate": comment.score, "create_time": comment.create_time.strftime(DATE_TIME_FMT),
            "user_id": comment.user_id, "user_name": comment.user.username,
            "avatar": comment.user.extenduserinfo.avatar if hasattr(comment.user, 'extenduserinfo') else None,
            "like_count": comment.commentlike__id__count, "is_like": is_like(comment)
        } for comment in comments
    ]
    if book_id is None:
        for c, d in zip(comments, comment_dicts):
            book = c.book
            d["book_info"] = {"book_id": book.id, "title": book.title, "cover_url": get_url(req, book.cover_uri)}

    return comment_dicts


def fetch_comments(req: WSGIRequest, page, page_size, order_by="like_count", book_id=None, user_id=None, current_user_id=None):
    if page_size > 100:
        raise FormException("单页不能超过100条")
    order_by_set = {"like_count", "create_time"}
    if order_by not in order_by_set:
        raise FormException("不支持的排序方式")
    offset, limit = page2offset(page, page_size)
    total_count, comments = comment_dao.fetch_comments(offset, limit, order_by, book_id=book_id, user_id=user_id)
    comment_ids = [comment.id for comment in comments]
    liked_comment_id_set = set()
    if current_user_id is not None:
        liked_comment_ids = CommentLike.objects.filter(
            comment_id__in=comment_ids, user_id=current_user_id,
        ).values_list("comment_id", flat=True)
        liked_comment_id_set = set(liked_comment_ids)
    comment_dicts = comment_model2dict(req, comments, lambda comment: comment.id in liked_comment_id_set, book_id=book_id)

    return total_count, comment_dicts
